import { Action } from 'redux';

import { ModelOptions, Reducers } from './types';

type A = Action<string> & { data: any };

export default <State = any>(opts: ModelOptions<State>) => {
  const { namespace, reducers = {} } = opts;
  const _reducers: Reducers<State> = {};
  Object.keys(reducers).forEach((key: string) => (
    _reducers[`${namespace}/${key}`] = reducers[key]
  ));
  return (state: State = opts.state, action: A) => {
    const { type } = action;
    const reducer = _reducers[type];
    return reducer ? { ...reducer(state, action) } : state;
  }
}
